import { adminMenus } from '@/api/system/menu/index'
import { constantRouterComponents } from './modules'
import router, { routes } from '@/router/'
import store from '@/store'
import { notFound } from '@/router/staticModules/error'
import common from '@/router/staticModules/'
import { RouteRecordRaw } from 'vue-router'
import { Empty } from 'ant-design-vue'
import { toHump } from '@/utils/common'
import { RouterTransition } from '@/components/transition'

/**
 * 异步生成菜单树， 方案二
 * @param dataList
 */
export const list2tree = (items) => {
  return items.map((item) => {
    const { name, routePath, children, code, icon, meta, hidden } = item;
    let path = '';
    if (/http(s)?:/.test(routePath)) {
      path = routePath
    } else {
      path = routePath.startsWith('/') ? routePath : '/' + routePath
      path = [...new Set(path.split('/'))].join('/')
    }
    const component = children && children.length
      ? RouterTransition
      : constantRouterComponents[path] || Empty
    return {
      path: path,
      // 路由名称，建议唯一
      name: `${routePath ? toHump(routePath) : path}-${item.code}`,
      children: item.children && item.children.length > 0 ? list2tree(item.children) : [],
      // 该路由对应页面的 组件 (动态加载)
      component: component,
      props: true,
      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: meta?.title || name,
        icon: icon || 'icon-dashboard',
        // hiddenHeaderContent: hiddenHeaderContent,
        // permission: item.actions || []
        hidden: meta?.hidden || hidden,
        reload: false,
        componentName: component.name,
        // TODO 简单模拟CRUD权限：创建（Create）、更新（Update）、读取（Retrieve）和删除（Delete）操作，可以自行修改查看页面效果
        permission:
          item.resourceList
      }
    }
  })
}


/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
  return new Promise((resolve, reject) => {
    adminMenus()
      .then((result) => {
        const menuNav: any = []
        //      后端数据, 根级树数组,  根级 PID
        // listToTree(data, childrenNav, 0)
        // rootRouter.children = childrenNav
        const  routeList = list2tree(result)
        routeList.forEach((item) => {
          // 设置模块重定向到菜单
          if (item.children?.length > 0 && !item.redirect) {
            // item.redirect = { name: item.children[0].name }
            item.redirect = item.children[0].path
          }
        })
        const layout = routes.find((item) => item.name == 'Layout')!
        // const routes = [...common,...routeList]
        // routes.forEach(item => router.addRoute('Layout', item))
        // && !res.modelCode

        layout.children = [...common, ...routeList]

        router.addRoute(layout)
        router.addRoute(notFound)
        resolve(layout.children as RouteRecordRaw[])
      })
      .catch((err) => {
        reject(err)
      })
  })
}

export const addR = () => {

}

export const editR = (routeList) => {

}
